package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.dto.PasswordEditDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.LoginFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void editPassword(PasswordEditDTO passwordEditDTO) {
        //设置当前用户的id
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
        //判断旧密码是否正确
        String passWork = employeeMapper.getEmpById(BaseContext.getCurrentId()).getPassword();
        if (!DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes()).equals(passWork)) {
            throw new LoginFailedException(MessageConstant.PASSWORD_EDIT_FAILED);
        }
        //判断新密码和旧密码是否相同
        if (passwordEditDTO.getNewPassword().equals(passwordEditDTO.getOldPassword())) {
            //相同 修改失败
            throw new LoginFailedException("新密码与原密码相同!");
        }
        //把密码改成密文
        String newPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes());
        passwordEditDTO.setNewPassword(newPassword);

        //保存到数据库
        employeeMapper.editPassword(passwordEditDTO);
    }

    /**
     * 员工分页查询
     *
     * @param ep
     * @return
     */
    @Override
    public PageResult pageEmp(EmployeePageQueryDTO ep) {
        //设置分页参数
        PageHelper.startPage(ep.getPage(), ep.getPageSize());
        //查询数据
        Page<Employee> emp = employeeMapper.pageEmp(ep);
        //封装响应数据
        return new PageResult(emp.getTotal(), emp.getResult());
    }

    /**
     * 修改员工状态
     *
     * @param status
     */
    @Override
    public void statusEmp(Integer status, Long id) {
        Employee emp = Employee.builder()
                .id(id)
                .status(status)
                .build();
        employeeMapper.updateEmp(emp);
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void addEmp(EmployeeDTO employeeDTO) {
        //创建员工对象
        Employee emp = new Employee();
        //拷贝数据
        BeanUtils.copyProperties(employeeDTO, emp);
        //补充数据
        //密码
        String password = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        emp.setPassword(password);
        //状态
        emp.setStatus(StatusConstant.ENABLE);
        //添加数据到数据库
        employeeMapper.addEmp(emp);
    }

    /**
     * 根据id查询员工信息
     *
     * @param id
     * @return
     */
    @Override
    public Employee getEmpById(Long id) {
        return employeeMapper.getEmpById(id);
    }

    /**
     * 编辑员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void updateEmp(EmployeeDTO employeeDTO) {
        //创建员工对象
        Employee emp = new Employee();
        //拷贝数据
        BeanUtils.copyProperties(employeeDTO, emp);
        //修改数据库数据
        employeeMapper.updateEmp(emp);
    }

}
